package cn.lingyangwl.agile.food.core.service.impl;

import cn.lingyangwl.agile.food.core.model.rqrs.cart.*;
import cn.lingyangwl.agile.food.core.model.rqrs.order.*;
import cn.lingyangwl.agile.food.core.service.*;
import cn.lingyangwl.agile.food.model.rqrs.store.*;
import cn.lingyangwl.agile.food.model.rqrs.table.*;
import cn.lingyangwl.agile.model.module.tenant.*;
import cn.lingyangwl.agile.msg.push.api.*;
import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author shenguangyang
 */
@Service
public class GoodsOrderServiceImpl implements GoodsOrderService {
    @Resource
    private GoodsService goodsService;
    @Resource
    private CartService cartService;
    @Resource
    private TableService tableService;
    @Resource
    private StoreService storeService;
    @Resource
    private MsgPushApi pushApi;

    @Override
    public CartOrderConfirmResp cartConfirmOrder(CartOrderConfirmReq req) {
        CartOrderConfirmResp resp = new CartOrderConfirmResp();
        CartOrderConfirmResp.Info orderInfo = new CartOrderConfirmResp.Info();
        resp.setOrderInfo(orderInfo);

        Optional<TableResp> table = Optional.ofNullable(tableService.getTable(req.getTableId()));
        String tableNo = table.map(TableBase::getCode).orElse("");

        CartListReq cartReq = new CartListReq().setCartType(req.getCartType())
            .setDeliveryWay(req.getDeliveryWay())
            .setCartIds(req.getCartIds()).setTableId(req.getTableId());
        CartResp cart = cartService.listCart(cartReq);
        CartResp.Info cartInfo = cart.getCartInfo();

        orderInfo.setBagPrice(cartInfo.getTotalBagPrice());
        orderInfo.setGoodsPrice(cartInfo.getTotalGoodsPrice());
        // TODO 暂时未开发优惠卷, 直接就是支付价格
        orderInfo.setPayPrice(cartInfo.getTotalPrice());
        orderInfo.setTotalNum(cartInfo.getCartTotalNum());
        orderInfo.setTableId(req.getTableId());
        orderInfo.setTableNo(tableNo);
        orderInfo.setGoodsList(cart.getGoodsList());

        StoreResp store = storeService.getStore(TenantContext.get().getTenantId());
        resp.setStore(store);

        // 获取模板id, 比如微信小程序需要用户主动订阅才能推送成功
        List<String> templateIds = pushApi.listTemplateIdsByCodes(
            NoticeCodeEnum.ORDER_PAY_SUCCESS, NoticeCodeEnum.ORDER_REFUND_SUCCESS
        );
        resp.setTemplateList(templateIds);
        return resp;
    }

    @Override
    public CartOrderResp saveCartOrder(CartOrderSaveReq req) {
        CartOrderResp resp = new CartOrderResp();
        resp.setOrderId(1L);
        return resp;
    }
}
